import { ref } from "vue";
import { Map, View } from "ol";
import { defaults as defaultControls, OverviewMap } from "ol/control";
import { Tile as TileLayer } from "ol/layer";
import { WMTS } from "ol/source";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import { getTopLeft } from "ol/extent";
import { get as getProjection } from "ol/proj";

interface UseMapInitializationProps {
  center: [number, number];
  zoom: number;
  mapKey: string;
}

export function useMapInitialization(props: UseMapInitializationProps) {
  const map = ref<Map | null>(null);
  const tdtLayer = ref<TileLayer<WMTS> | null>(null);

  const initMap = (mapRef: HTMLElement) => {
    return new Promise<void>((resolve, reject) => {
      try {
        const tdtLayerInstance = new TileLayer({
          source: new WMTS({
            url: `http://t1.tianditu.gov.cn/img_c/wmts?tk=${props.mapKey}`,
            layer: "img",
            matrixSet: "c",
            format: "tiles",
            projection: "EPSG:4326",
            tileGrid: new WMTSTileGrid({
              origin: getTopLeft(getProjection("EPSG:4326")!.getExtent()),
              resolutions: Array(21)
                .fill(0)
                .map((_, z) => 1.40625 / Math.pow(2, z)),
              matrixIds: Array.from({ length: 21 }, (_, z) => z.toString()),
            }),
            style: "default",
            wrapX: true,
          }),
        });
        tdtLayer.value = tdtLayerInstance;

        const overviewMapControl = new OverviewMap({
          layers: [tdtLayerInstance],
          collapsed: false,
          collapseLabel: "\u00BB",
          label: "\u00AB",
          view: new View({
            projection: "EPSG:4326",
            center: props.center,
            zoom: 6,
          }),
          className: "ol-overviewmap ol-custom-overviewmap",
        });

        map.value = new Map({
          target: mapRef,
          view: new View({
            center: props.center,
            zoom: props.zoom,
            projection: "EPSG:4326",
          }),
          layers: [tdtLayerInstance],
          controls: defaultControls().extend([overviewMapControl]),
        });

        resolve();
      } catch (error) {
        reject(error);
      }
    });
  };

  return {
    map,
    tdtLayer,
    initMap,
  };
}
